import React, { useImperativeHandle, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Form, Button, Row } from 'antd';
import { toCDB, formateDate } from './utils/util';
import GlobalFormItem from './GlobalFormItem';
import { isArray } from 'lodash';

const dateComponetType = {
  monthpicker: 'YYYY-MM',
  rangepicker: 'YYYY-MM-DD',
  datepicker: 'YYYY-MM-DD',
  yearpicker: 'YYYY',
  timepickerrange: 'HH:mm'
};

const dataArrayType = [
  'rangepicker'
]

const GlobalForm = React.forwardRef((props, ref) => {
  const formRef = useRef();
  const { formSet, column, loading, cancelBtnText, initialValues, children, gutter, submitCall, cancelCall, toolBarRender, defaultFooterBar, labelBasicSpan, totalSpan, ...restProps } = props;
  console.log("initialValues", initialValues)
  const dateFields = {}; //日期的字段
  const newFormProps = {
    onFinish: fieldsValue => {
      collectDateField();
      submitCall(formatValues(fieldsValue))
    },
    initialValues
  }

  const formItemProps = {
    column,
    labelBasicSpan,
    totalSpan
  };

  useEffect(() => {

    // 收集需要转换日期格式的数据
    collectDateField();
  }, []);

  useImperativeHandle(ref, () => ({
    reset,
    formatValues,
    collectDateField,
    submit: () => {
      formRef.current.validateFields().then(values => {
        collectDateField();
        const params = formatValues(values);
        submitCall(params)
      }).catch(errorInfo => {
        console.log(errorInfo)
      })
    },
    ...formRef.current,
  }));

  // 收集日期字段
  const collectDateField = () => {
    formSet.forEach((itemSet, i) => {
      const { name, type, listFormSet, models = [] } = itemSet;
      if (Object.keys(dateComponetType).includes(type)) {
        dateFields[name] = type;
      }
      if (type === 'list') {
        dateFields[name] = {};
        listFormSet.forEach(listItemSet => {
          if (Object.keys(dateComponetType).includes(listItemSet.type)) {
            dateFields[itemSet.name][listItemSet.name] = listItemSet.type
          }
        })
      }
    });
  }

  // 转换表单值
  const formatValues = fieldsValue => {
    Object.keys(fieldsValue).forEach(key => {
      let value = fieldsValue[key];
      if (typeof value === 'string') {
        value = value.replace(/(^\s*)|(\s*$)/g, ''); // 去空格
        fieldsValue[key] = toCDB(value); // 统一转半角
      }
    });

    // 转换日期moment
    Object.keys(dateFields).forEach((field) => {
      const type = dateFields[field];
      if (typeof type === 'string')
        fieldsValue[field] = formateDate(fieldsValue[field], dateComponetType[type])
      else if (typeof type === 'object') {
        const childFields = Object.keys(type);
        let dataList = fieldsValue[field];

        fieldsValue[field] = dataList.map(item => {
          const _item = {};
          childFields.forEach((child_field) => {
            const child_type = childFields[child_field];
            _item[child_field] = formateDate(item[child_field], dateComponetType[child_type])
          })
          return {
            ...item,
            ..._item
          }
        })
      }
      //处理数组
      if (dataArrayType.includes(type) && isArray(fieldsValue[field])) {
        const dataFrom = formSet.find(from => from.name == field);
        if (dataFrom) {
          const { models = [] } = dataFrom
          const [startTime = 'startTime', endTime = 'endTime'] = models
          [startTime, endTime] = fieldsValue[field];
          fieldsValue = {
            ...fieldsValue,
            startTime,
            endTime
          }
          delete fieldsValue[field]
        }
      }
    })


    return fieldsValue;
  }




  // 重置
  const reset = () => {
    const form = formRef.current;
    form.resetFields();
    cancelCall(form.getFieldsValue());
  }

  return (
    <div>
      <Form ref={formRef}  {...newFormProps} {...restProps}>
        <div style={{ flex: 1 }} >
          <Row gutter={gutter}>
            {
              formSet.filter(v => v.type).map((itemSet) => (
                <GlobalFormItem key={itemSet.name} {...formItemProps} itemSet={itemSet} />))
            }
            {children}
          </Row>
        </div>


        {/* <Divider /> */}
        {
          defaultFooterBar && (
            <div className="button-box-shadow">
              {toolBarRender}
              <Button size="large" className="mr10" onClick={reset}>{cancelBtnText || '重置'}</Button>
              <Button size="large" type="primary" htmlType="submit" loading={loading}>保存</Button>
            </div>
          )
        }
      </Form>
    </div>
  );
});

GlobalForm.propTypes = {
  formSet: PropTypes.array, // 表单配置项
  column: PropTypes.number, // 一行显示几列
  cancelCall: PropTypes.func, // 取消回调
  submitCall: PropTypes.func, // 提交回调
  loading: PropTypes.bool, // 正在保存
  initialValues: PropTypes.object, // 表单初始值
  cancelBtnText: PropTypes.string, // 取消按钮文案
  gutter: PropTypes.number,
  toolBarRender: PropTypes.object, // 底部按钮工具栏
  defaultFooterBar: PropTypes.bool, // 底部按钮工具栏
  labelBasicSpan: PropTypes.number,
  totalSpan: PropTypes.number,
};

GlobalForm.defaultProps = {
  formSet: [],
  column: 3,
  cancelCall: () => { },
  submitCall: () => { },
  loading: false,
  cancelBtnText: '',
  initialValues: {},
  gutter: 0,
  toolBarRender: null,
  defaultFooterBar: true,
  labelBasicSpan: 8,
  totalSpan: 22
};

export default GlobalForm;
